//
//  UIDevice+IPAddress.m
//  NurseOperator
//
//  Created by Lee on 14-1-2.
//  Copyright (c) 2014年 Lee. All rights reserved.
//


#import "UIDevice+Supplement.h"
#import "ECTSSKeychain.h"
#import "OpenUDID.h"
#include <netdb.h>
#include <net/if.h>
#import <arpa/inet.h>
#include <ifaddrs.h>
#include <dlfcn.h>

#define mUDID @"AppUDID"
#define mUDIDKey  @"UDID"
#define mServices @"massvig_noqsystem"

@implementation UIDevice (Supplement)

+ (NSString *)getIPAddress{
//    return @"192.168.0.1";
    BOOL success;
    struct ifaddrs *addrs;
    const struct ifaddrs *cursor;
    
    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK)==0) {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                if ([name isEqualToString:@"en0"]) {
                    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
                }
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return nil;
}

+ (NSString *)getUDID{
    static NSString *udid = nil;
    if (!udid) {
        udid = [[ECTSSKeychain passwordForService:mServices account:mUDID] copy];
        [[NSUserDefaults standardUserDefaults] setObject:mAvailableString(udid) forKey:mAvailableString(udid)];
        if (nil == udid||![udid length]) {
            udid = [[OpenUDID value] copy];
            [ECTSSKeychain setPassword:udid forService:mServices account:mUDID];
        }
    }
    return udid;
}

@end
